package com.utils;

import java.util.Map;
import javax.servlet.http.HttpSession;

import org.apache.shiro.session.Session;

public class RsaUtils {
	
	static final String RSA_PRIVATE_KEY = "rsaPrivateKey";
	
	public static String decryptByPrivateKey(String password, HttpSession session){
		String privateKey = (String) session.getAttribute(RSA_PRIVATE_KEY);
		return decryptByPrivateKey(password, privateKey);
	}
	
	public static String decryptByPrivateKey(String password, Session session){
		String privateKey = (String) session.getAttribute(RSA_PRIVATE_KEY);
		return decryptByPrivateKey(password, privateKey);
	}
	
	public static String decryptByPrivateKey(String password, String privateKey){
		String pwd = null;
		System.out.println("privateKeyval : " + privateKey);
		try {
			byte[] plaintext = RSA.decryptByPrivateKey(Encodes.decodeBase64(password), privateKey);
			pwd = new String(plaintext, "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return pwd;
	}
	
	public static String setRSAKey(HttpSession session) {
		String modulus = "";
		try {
			Map<String, Object> keyMap = RSA.initKey();  
			String publicKey = RSA.getPublicKey(keyMap);  
			String privateKey = RSA.getPrivateKey(keyMap);
			
			System.out.println("publicKey : " + publicKey);
			System.out.println("privateKey : " + privateKey);
			
			session.setAttribute(RSA_PRIVATE_KEY, privateKey);
			
			modulus = RSA.getRSAPublicKeyModulusToHex(publicKey);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return modulus;
	}
}
